import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { message, notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  getAccessCodesApi,
  getCaptChaImage,
  getUserinfoApi,
  getUserInfoApi,
  getUserRoutesApi,
  loginApi,
  logoutApi,
  userLogin,
} from '#/api';
import { $t } from '#/locales';
import { router } from '#/router';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const routerr = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const { accessToken } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult, accessCodes] = await Promise.all([
          fetchUserInfo(),
          getAccessCodesApi(),
        ]);

        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await routerr.push(userInfo.homePath || DEFAULT_HOME_PATH);
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    router.replace({
      path: '/auth/login',
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  const loginloading = ref(false);
  const captchaImage = ref({
    image: '',
    uuid: '',
  });

  const refreshCaptchaImage = async () => {
    const {
      data: { img, uuid },
    } = await getCaptChaImage();
    captchaImage.value.image = `data:image/;base64,${img}`;
    captchaImage.value.uuid = uuid;
  };

  async function fetchUserinfo() {
    const userInfo = await getUserinfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  const authlogin = async (
    params: Parameters<typeof userLogin>[0],
    // onSuccess?: () => Promise<void> | void,
  ) => {
    loginloading.value = true;
    const {
      data: { code, token, msg },
    } = await userLogin(params);
    if (code === 200) {
      message.success('恭喜你，登录成功🎉');
      const accessStore = useAccessStore();
      accessStore.setAccessToken(token);
      // 获取用户信息 获取路由列表
      const [data1, data2] = await Promise.all([
        getUserinfoApi(),
        getUserRoutesApi(),
      ]);
      console.warn(data1);
      console.warn(data2);
      router.replace(DEFAULT_HOME_PATH);
    } else if (code === 500) {
      message.error(msg);
      refreshCaptchaImage();
    }
    // if (token) {
    //   const accessStore = useAccessStore();
    //   accessStore.setAccessToken(token);
    //   const data = await getUserInfoApi();
    //   console.log('data:', data);
    // }
  };

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    loginloading,
    captchaImage,
    refreshCaptchaImage,
    authlogin,
    fetchUserinfo,
  };
});
